package web.config;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import web.entity.Security_UserDetail;
import web.entity.User2RoleDo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author cc
 * @create 2022/9/30 18:50
 */
@Component("cnkiAuthType")
public class SecurityAuthType {
    /**
     * 同时具有所有权限才可放行
     * @param roles 接口需要的权限数组
     * @return
     */
    public boolean ingroupAnd(String... roles) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Security_UserDetail detail = (Security_UserDetail)authentication.getPrincipal();
        List<User2RoleDo> hisRoles = detail.getRoles();
        List<String> hisRolesStr = new ArrayList<>();
        for (User2RoleDo hisRole :hisRoles) {
            hisRolesStr.add(hisRole.getRoleId().toString());
        }
        return hisRolesStr.containsAll(Arrays.asList(roles));
    }

    /**
     * 具有任意权限都可放行
     * @param roles 接口需要的权限数组
     * @return
     */
    public boolean inGroupOr(String... roles) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Security_UserDetail detail = (Security_UserDetail)authentication.getPrincipal();
        List<User2RoleDo> hisRoles = detail.getRoles();
        List<String> hisRolesStr = new ArrayList<>();
        for (User2RoleDo hisRole :hisRoles) {
            hisRolesStr.add(hisRole.getRoleId().toString());
        }
        for (String requireRole :roles) {
            if (hisRolesStr.contains(requireRole)){
                return true;
            }
        }
        return false;
    }
}
